var he = require('he');

const candidate_biz = [
  'MzI2NDk5NzA0Mw==',
  'MzIzOTA3NTA5Mg==',
  'MjM5ODUxMjExMA=='
]

var cur = -1;

// const jscode = `<script>alert('Start');\nwindow.setTimeout(function(){\nalert('Go');\ndocument.body.innerHTML = "<textarea>"+document.body.innerHTML+"</textarea>"},10000);</script>`;
// const jscode = `<script>alert('Start');\nwindow.setTimeout(function(){\nalert('Go');\ndocument.body.innerHTML = "<textarea>"+msgList+"</textarea>"},10000);</script>`;

module.exports = {
  summary: 'a rule to hack response',
  *beforeSendResponse(requestDetail, responseDetail) {
    if (requestDetail.url.startsWith('https://mp.weixin.qq.com/mp/profile_ext?action=home&')) {
      let newResponse = responseDetail.response;
      cur = (cur+1) % candidate_biz.length;
      //let choose_biz = candidate_biz[parseInt(Math.random() * candidate_biz.length)];
      let choose_biz = candidate_biz[cur];
      let forward_url = `https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=${choose_biz}&scene=126&bizpsid=0#wechat_redirect`;
      let body = newResponse.body.toString();
      // newResponse.body = body.replace('</head>','<meta http-equiv="refresh" content="5;url='+forward_url+'" /></head>');
      newResponse.body = body.replace('</body>','<script>window.setTimeout(function(){window.location.replace("'+forward_url+'");},5000);</script></body>');
      try{
        let pub_id = eval(body.replace(/[\s\S]*var username = ([^;]*?);[\s\S]*/img, '$1'));
        let pub_name = eval(body.replace(/[\s\S]*var nickname = ([^;]*?);[\s\S]*/img, '$1'));
        let pub_biz = eval(body.replace(/[\s\S]*var __biz = ([^;]*?);[\s\S]*/img, '$1'));
        let pub_headimg = eval(body.replace(/[\s\S]*var headimg = ([^;]*?);[\s\S]*/img, '$1'));
        let msg_list = JSON.parse(he.decode(body.replace(/[\s\S]*var msgList = '([^']*?)';[\s\S]*/img, '$1')));
        let latest_msg = msg_list['list'][0];
        let latest_updated = new Date(latest_msg['comm_msg_info']['datetime']*1000);
        let latest_articles = [{
          'title' : latest_msg['app_msg_ext_info']['title'],
          'cover' : latest_msg['app_msg_ext_info']['cover'],
          'content_url' : (he.decode(latest_msg['app_msg_ext_info']['content_url'])).replace(/\\\//g,'/'),
          'source_url' : (he.decode(latest_msg['app_msg_ext_info']['source_url'])).replace(/\\\//g,'/'),
          'author' : latest_msg['app_msg_ext_info']['author']
        }].concat(latest_msg['app_msg_ext_info']['multi_app_msg_item_list'].map(x=>{
          return {
            'title' : x['title'],
            'cover' : x['cover'],
            'content_url' : (he.decode(x['content_url'])).replace(/\\\//g,'/'),
            'source_url' : (he.decode(x['source_url'])).replace(/\\\//g,'/'),
            'author': x['author']
          }
        }));
        console.log(pub_name,'于',latest_updated,'发布：');
        for(let a of latest_articles){
          console.log(a['title']);
          console.log(a['content_url']);
        }
      }catch(e){
        console.error(e);
      }

      return new Promise((resolve, reject) => {
        // setTimeout(() => { // delay
          resolve({ response: newResponse });
        // }, 1000);
      });
    }
  },
};